<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\AdminConfig;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\StaffRole;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use addons\qingdongams\model\Field;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\StaffRule;
use fast\Http;
use think\Cache;
use think\Config;
use think\Hook;

/**
 * 公共接口
 */
class Common extends StaffApi {
	protected $noNeedLogin = ['init','getConfig','getGeocoder'];
	protected $noNeedRight = '*';


	/**
	 * 加载初始化
	 * @param string $version 版本号
	 * @param string $lng 经度
	 * @param string $lat 纬度
	 */
	public function init() {
		if ($version = $this->request->request('version')) {
			$lng = $this->request->request('lng');
			$lat = $this->request->request('lat');

			//配置信息
			$upload = Config::get('upload');
			//如果非服务端中转模式需要修改为中转
			if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
				//临时修改上传模式为服务端中转
				set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

				$upload = \app\common\model\Config::upload();
				// 上传信息配置后
				Hook::listen("upload_config_init", $upload);

				$upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
			}

			$upload['cdnurl']    = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
			$upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

			$content = [
				'citydata'    => Area::getCityFromLngLat($lng, $lat),
				'versiondata' => Version::check($version),
				'uploaddata'  => $upload,
				'coverdata'   => Config::get("cover"),
			];
			$this->success('', $content);
		} else {
			$this->error(__('Invalid parameters'));
		}
	}


	/**
	 * 上传文件
	 * @ApiMethod (POST)
	 * @param File $file 文件流
	 */
    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        $name = input('name');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload(null);
            if (stristr($attachment->mimetype, 'image')) {
                $types = 'image';
            } else {
                $types = 'file';
            }
            $staff = Staff::info();
            $params = array(
                'name' => $name ?: $attachment->filename,
                'save_name' => $attachment->url,
                'size' => $attachment->filesize,
                'types' => $types,
                'file_path' => $attachment->url,
                'create_staff_id' => empty($staff) ? 0 : $staff->id
            );
            $attachment = new \addons\qingdongams\model\File();
            $attachment->data(array_filter($params));
            $attachment->save();

            $fileId = $attachment->id;

        } catch (UploadException $e) {
            return json_encode(['code' => 0, 'msg' => $e->getMessage()]);
        }
        $this->success(__('Uploaded successful'), [
            'id' => $fileId,
            'name' => $params['name'],
            'url' => cdnurl($attachment->file_path, true)
        ]);
    }


	//select 字段表
	public function selectOption() {
		$fields = Field::where([])->select();
		$data   = [];
        foreach ($fields as $v) {
            $data[$v['type']][$v['name']] = json_decode($v['data']);
        }

        $this->success('请求成功', $data);
	}


	//获取form表单
	public function getForm() {
		$type = input('type', 'leads');//leads 线索 customer 客户 contacts 联系人 contract 订单 examine回款 product产品
		$form = Form::where(['type' => $type])->find();

		$this->success('请求成功', json_decode($form['data'], true));
	}


	//获取员工
	public function getSelectStaff() {
		$name  = input('name');
		$department_id = input('department_id');
		$where = ['status' => 1];
		if ($name) {
			$where['name'] = ['like', "%{$name}%"];
		}
		if ($department_id) {
			$where['department_id'] = ['in',explode(',',$department_id)];
		}

		$staffs = \addons\qingdongams\model\Staff::where($where)->field('id,name,department_id,nickname,post,img,mobile')->select();

		$this->success('请求成功', $staffs);
	}

    //获取员工权限
    public function getStaffRule(){
       $staff_id= $this->auth->id;
       $staff=\addons\qingdongams\model\Staff::get($staff_id);
        $role=StaffRole::where(['id'=>$staff['role']])->find();
        $rules=isset($role['rules'])?explode(',',$role['rules']):[];
        $row=StaffRule::where(['pid'=>0])->column('name','id');
        $staffRules=StaffRule::where(['pid'=>['neq',0],'type'=>['neq','data']])->select();
        $roleList=[];
        foreach ($staffRules as $v) {
            $pname = $row[$v['pid']] ?? '';
            if ($pname == 'menu') {
                $roleList[$pname][$v['name']] = [
                    'name' => $v['title'],
                    'is_show' => in_array($v['id'], $rules) ? 1 : 0
                ];
            } else {
                $roleList[$pname][$v['type']][$v['name']] = [
                    'name' => $v['title'],
                    'is_show' => in_array($v['id'], $rules) ? 1 : 0
                ];
            }
        }
        $this->success('请求成功',$roleList);
    }

    /**
     * 设置数据缓存
     */
    public function setCacheData()
    {

        $type = input('type');
        $id = $this->auth->id;
        $params = $this->request->post();
        unset($params['type']);
        Cache::set($type . $id, json_encode($params), 60*60 * 3);
        $this->success('设置成功');
    }

    /**
     * 读取数据缓存
     */
    public function getCacheData()
    {
        $type = input('type');
        $id = $this->auth->id;
        $data=json_decode(Cache::get($type . $id),true);
        if(empty($data)){
            $data=null;
        }
        $this->success('获取成功', $data);
    }

    /**
     * 获取后台配置
     */
    public function getConfig(){
        $map_key = AdminConfig::getConfigValue('map_key','wechat');
        $appid =AdminConfig::getConfigValue('appid','wechat');
        $mobile_name =AdminConfig::getConfigValue('user_name','user');
        $data=[
            'map_key'=>$map_key ? $map_key : '',
            'appid'=>$appid ? $appid : '',
            'mobile_name'=>$mobile_name? $mobile_name :'E售后'
        ];
        $this->success('请求成功',$data);
    }

    /**
     * 逆解析
     */
    public function getGeocoder(){
        $map_key=AdminConfig::getConfigValue('map_key',  AdminConfig::TYPE_WECHAT);
        if(empty($map_key)){
            $this->error('腾讯地图key未设置，请联系管理员设置！');
        }
        $lat=input('lat');
        $lng=input('lng');
        if(empty($lat) || empty($lng)){
            $this->error('经度或纬度不能为空');
        }
        $url='https://apis.map.qq.com/ws/geocoder/v1/';
        $params = ['location' => $lat.','.$lng, 'get_poi' => 1, 'key' => $map_key];
        $result=Http::get($url,$params);
        $result=json_decode($result);
        $this->success('请求成功',$result);
    }
    /**
     *省市区转地址
     */
    public function addressGeocoder(){
        $map_key=AdminConfig::getConfigValue('map_key',  AdminConfig::TYPE_WECHAT);
        if(empty($map_key)){
            $this->error('腾讯地图key未设置，请联系管理员设置！');
        }
        $address=input('address');
        $url="https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key={$map_key}";
        $result=file_get_contents($url);
        $result=json_decode($result,true);

        $this->success('请求成功',$result);
    }

    /**
     * 获取时间
     */
    public function getTimes()
    {
        $times = input('times');
        $times = setTimes($times, 'date');
        $this->success('请求成功', ['times' => $times]);
    }

    /**
     * 获取搜索字段
     */
    public function getSearchFields(){
        $type=input('type');//leads
//        'field'=>['like',"main_%"],
        $fields=FormField::where(['types'=>$type,'list_show'=>1,'info_type'=>'main'])->select();
        $this->success('请求成功',$fields);
    }
}
